package sort;

import java.util.Arrays;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: 杰哥
 * Date: 2020/4/8
 * Time: 9:49
 */
public class MergeSort {

    public static void main(String[] args) {
        int arr[] = {8, 4, 5, 7, 1, 3, 6, 2, 0};
//        int arr[] = new int[20000000];
        int temp[] = new int[arr.length];

//        for (int i = 0; i < 20000000; i++) {
//            arr[i] = (int)(Math.random() * 20000000);
//        }

        Date date1 = new Date();
        mergeSort(arr, 0, arr.length - 1, temp);
        Date date2 = new Date();
        System.out.println("用时：" + (date2.getTime() - date1.getTime()) + "毫秒" );
//        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(temp));
    }

    //分+合方法
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if(left < right) {
            int mid = (left + right) / 2;//中间索引
            //向左递归进行分解
            mergeSort(arr, left, mid, temp);
            //向右递归进行分解
            mergeSort(arr, mid+1, right, temp);
            //合并
            merge(arr, left, mid, right, temp);
        }
    }

    /**
     *
     * @param arr 需要排序的元素数组
     * @param left 左边有序序列的初始索引
     * @param mid   中间索引
     * @param right 右边有序序列的初始索引
     * @param temp
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        //初始化i，左边有序序列的初始下标，指向左边需要排序的数的下标
        int i = left;
        //初始化j，右边有序序列的初始下标，指向右边需要排序的数的下标
        int j = mid + 1;
        //指向temp数组的当前索引
        int t = 0;

        //1.先把左右两边（有序）的数据按照顺序填充到temp数组，直到其中一边处理完毕为止
        while(i <= mid && j <= right) {
            if(arr[i] <= arr[j]) {
                temp[t] = arr[i];
                t += 1;
                i +=1;
            }else {
                temp[t] = arr[j];
                t += 1;
                j += 1;
            }
        }

        //2.把有剩余数据的一边的数据依次全部填充到temp
        while (i <= mid) { //左边的有序
            temp[t] = arr[i];
            t += 1;
            i +=1;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t += 1;
            j += 1;
        }


        //将temp数组的元素拷贝到arr
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[t];
            t += 1;
            tempLeft += 1;
        }

    }

}
